package db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import beans.Resource;
import beans.ResourceSchedule;

public class ResourceDAO {
	public static String addResource(String description) {
		try {
			Connection c = DataUtils.getDBConnection();
			
			PreparedStatement st = c.prepareStatement(SQL.map.get("IRESOURCE.sql").toString());
			st.setString(1, description);
				
			st.executeUpdate();
		
			st.close();
			    
		    return "";
		} catch (SQLException s) {
			int errorCode = s.getErrorCode();
			if (errorCode == 1) {
				return "Resources must be unique.";
			} else {
				return "" + errorCode;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static List getResourceSchedules() {
		try {			
			Connection c = DataUtils.getDBConnection();
			
			PreparedStatement st = c.prepareStatement(SQL.map.get("SRESOURCESCHEDULE.sql").toString());
			
			ResultSet rs = st.executeQuery();
		    
		    List resourceScheduleList = new ArrayList();
		    
		    while (rs.next()) {
			    String rd = rs.getString("RD"); 
			    Date startDate = rs.getDate("START_DATE");
			    Date endDate = rs.getDate("END_DATE");
			    String td = rs.getString("TD");
			    String pt = rs.getString("PT");
			    Calendar sDate = Calendar.getInstance(); sDate.setTime(startDate);
			    Calendar eDate = Calendar.getInstance(); eDate.setTime(endDate);
			    resourceScheduleList.add(new ResourceSchedule(rd, sDate, eDate, td, pt));
		    }

		    rs.close();
		    st.close();
		    
		    return resourceScheduleList;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static List getResources() {
		try {
			Connection c = DataUtils.getDBConnection();
			
			PreparedStatement st = c.prepareStatement(SQL.map.get("SRESOURCE.sql").toString());
			
			ResultSet rs = st.executeQuery();
		    
		    List resources = new ArrayList();
		    
		    while (rs.next()) {
		    
		    	
		    	resources.add(new Resource(rs.getInt("RESOURCE_ID"), rs.getString("DESCRIPTION")));
		    }
		    
		    rs.close();
		    st.close();
		    
		    return resources;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


}
